import { Button, Form, Input, Modal, Spin, message } from "antd";
import { useState } from "react";
import { min_app_fs } from "@linksaas-minapp/api";
import { FolderOpenOutlined } from "@ant-design/icons";
import { getSftpApi, getToken } from "../utils/client";


export interface UploadModalProps {
    curClientId: string
    curPath: string
    onOk: () => void;
    onCancel: () => void;
}

function UploadModal(props: UploadModalProps) {
    const [path, setPath] = useState("");
    const [inUpload, setInUpload] = useState(false);

    const choicePath = async () => {
        const selected = await min_app_fs.openDialog("上传文件", false);
        if (selected == null || Array.isArray(selected)) {
            return;
        }
        setPath(selected as string);
    };

    const upload = async () => {
        const api = getSftpApi();
        setInUpload(true);
        try {
            await api.sftpUploadPost({
                sftpDownloadPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    path: props.curPath,
                    localPath: path,
                },
            });
            setInUpload(false);
            props.onOk();
        } catch (e) {
            console.log(e);
            setInUpload(false);
            message.error("上传文件失败");
        }
    };

    return (
        <Modal open title="上传文件" okText="上传" okButtonProps={{ disabled: path.trim() == "" || inUpload }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }} onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                upload();
            }}>
            {inUpload == true && (
                <div>
                    <Spin />上传中......
                </div>
            )}
            {inUpload == false && (
                <Form>
                    <Form.Item label="本地文件">
                        <Input value={path} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setPath(e.target.value.trim());
                        }} addonAfter={
                            <Button type="text" style={{ padding: "0px 0px", height: "20px" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                choicePath();
                            }}><FolderOpenOutlined /></Button>
                        } />
                    </Form.Item>
                </Form>
            )}

        </Modal>
    );
}

export default UploadModal;